#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os.path
import re
import tornado.database
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import base64
import hashlib
import basehandler
import json

# Admin Handler
class AdminHandler(basehandler.BaseHandler):
    def __init__(self,a,r,**k):
        basehandler.BaseHandler.__init__(self,a,r,**k)
        self.allow(9)
            

    def get(self,args):
        if args:
            if 'tags' in args:v = self.tags("show")
            if 'tags/add' in args:self.tags("add")
            if 'tags/apply' in args:self.tags("apply")
            if 'tags/delete' in args:self.tags("delete")
            self.render("admin_"+args+".html",val=v)
        else:
            uc = self.get_secure_cookie("center")
            self.render(uc+".html")

    def post(self,args):
        job,action = args.split("/")
        try:
            return {
                'tags':self.tags,
                }[job](action)
        except KeyError:
            pass
        self.redirect(action)

    def tags(self,action):
        """ 标签动作集
        """
        if action == "show":
            val = {}
            val['tags_type'] = ['其它','菜系','口味','材料','功效','配置']
            val['tags_set'] = self.db.query("select * from tags")
            return val
        
        if action == "add":
            _have = self.db.get("select * from tags where name=%s",self.get_argument("tagname"))
            if not _have:
                r = self.db.execute("insert into tags(`name`,`type`) values(%s,%s)",self.get_argument("tagname"),self.get_argument("type"))
                if r:
                    self.write(dict(code=r,msg="标签添加成功!"))
                else:
                    self.write(dict(code=r,msg="标签添加失败!"))
            else:
                r = self.db.execute("update tags set `delete`=0 ,`type`=%s where `name`=%s",self.get_argument("type"),self.get_argument("tagname"))
                self.write(dict(code=r,msg="标签添加失败!(当前标签已经添加过了,所以系统重新回收它到当前分类!确定后需要刷页面。)"))
            self.finish()

        if action == "apply":
            r = self.db.execute("update tags set `name`=%s where `id`=%s",self.get_argument("tagname"),self.get_argument("id"))
            self.write(str(r))
            self.finish()

        if action == "trash":
            r = self.db.execute("update tags set `delete`=1 where `id`=%s",self.get_argument("id"))
            self.write(str(r))
            self.finish()
            
        if action == "delete":
            r = self.db.execute("delete from tags where `id`=%s",self.get_argument("id"))
            self.write(str(r))
            self.finish()
                
